package net.yb.dao.impl;

import net.yb.dao.UserDao;
import net.yb.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户数据访问的实现类
 */
public class UserDaoImpl implements UserDao {
    @Override
    public void insertUser(User user) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yc12405", "root", "root");
            String sql = "insert into t_user (name, pwd, age, sex, height) values (?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getName());
            ps.setString(2, user.getPwd());
            ps.setInt(3, user.getAge());
            ps.setString(4, user.getSex());
            ps.setDouble(5, user.getHeight());
            ps.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User selectByName(String name) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yc12405", "root", "root");
            String sql = "select * from t_user where name=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ResultSet rs = ps.executeQuery(); // 返回结果集
            if(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPwd(rs.getString("pwd"));
                user.setAge(rs.getInt("age"));
                user.setSex(rs.getString("sex"));
                user.setHeight(rs.getDouble("height"));
                return user;
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
